﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq.Expressions;
using System.Text; 
using System.Web.Routing;
using System.Web.Mvc;

namespace SRF.UI.Html
{
    public static class ValidationExtensions
    {
        public static MvcHtmlString Validation<TModel>(this HtmlHelper htmlHelper, string jQcontainer = "")
        {
            return Validation(htmlHelper, typeof(TModel), jQcontainer);
        }
        public static MvcHtmlString Validation(this HtmlHelper htmlHelper, Type modelType, string jQcontainer = "")
        {
            ModelMetadataProvider provider = ModelMetadataProviders.Current;
            ModelMetadata containerMetadata = new ModelMetadata(provider, null, () => null, modelType, null);

            StringBuilder scriptBuilder = new StringBuilder();
            scriptBuilder.AppendLine("<script type='text/javascript'>");
            scriptBuilder.AppendLine("(function ($) {");

            foreach (var prop in modelType.GetProperties())
            {
                var metaData = containerMetadata.Properties.SingleOrDefault(m => m.PropertyName == prop.Name);
                if (metaData != null)
                {
                    var validationAttrs = htmlHelper.GetUnobtrusiveValidationAttributes(prop.Name.ToLower(), metaData);
                    if (validationAttrs.Count > 0)
                    {
                        scriptBuilder.AppendFormat("var ${0} = $(\"[name='{0}']\",'{1}');", prop.Name, jQcontainer);
                        foreach (var attr in validationAttrs)
                        {
                            scriptBuilder.AppendFormat("${0}.attr('{1}','{2}');", prop.Name, attr.Key, attr.Value);
                        }
                    }
                }
            }
            scriptBuilder.AppendLine("})(jQuery);");
            scriptBuilder.AppendLine("</script>");

            return new MvcHtmlString(scriptBuilder.ToString());
        }
    }
}